package cn.shop.core.service.impl;

import cn.shop.core.service.StaticPageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Map;

/**
 * Created by Administrator on 2016/10/1.
 */
public class StaticPageServiceImpl implements StaticPageService {
    private Configuration conf;
    private ServletContext servletContext;

    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.conf = freeMarkerConfigurer.getConfiguration();
    }

    public void outStaticPage(Map root, Integer id) {
        Writer out = null;
        try {
            Template template = conf.getTemplate("goodsinfo.html");
            String path = getPath("/html/" + id + ".html");
            File f = new File(path);
            File parentFile = f.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }

            out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");

            template.process(root, out);
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    //获取当前工程路径
    public String getPath(String name){

        return servletContext.getRealPath(name);
    }

    public void setServletContext(ServletContext servletContext) {
        this.servletContext=servletContext;

    }

}
